﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using KhatVongViet.Models;
using PagedList;
using System.Web.Security;

namespace KhatVongViet.Controllers
{
    public class AdministratorController : Controller
    {
        KhatVongVietEntities dataContext = new KhatVongVietEntities();
        GetData getData = new GetData();

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(UserModel user)
        {
            if (user.IsValid(user.UserName, user.Password))
            {
                FormsAuthentication.SetAuthCookie(user.UserName, user.RememberMe);
                return RedirectToAction("ManageArticle", "Administrator");
            }
            return View(user);
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Default", "Home");
        }

        public ActionResult ChangePassword()
        {
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ChangePassword(UserModel userModel)
        {
            var currentUser = dataContext.Users.FirstOrDefault(p => p.UserName == userModel.UserName);

            if (currentUser != null && currentUser.Password == userModel.Password)
            {
                if (userModel.NewPassword == userModel.ConfirmPassword)
                {
                    currentUser.UserName = userModel.UserName;
                    currentUser.Password = userModel.NewPassword;
                    dataContext.SaveChanges();
                    return RedirectToAction("ManageArticle", "Administrator");
                }
                return View();
            }
            return View();
        }

        public ActionResult CreateArticle()
        {
            bool logIn = HttpContext.Request.IsAuthenticated;
            if (logIn)
            {
                IEnumerable<SelectListItem> items = dataContext.Types
                                                        .Select(c => new SelectListItem
                                                        {
                                                            Value = c.TypeID,
                                                            Text = c.TypeName
                                                        });

                var query = dataContext.Types.Where(c => c.TypeID != "GocChiaSe_CXV").Select(c => new { c.TypeID, c.TypeName }).OrderBy(c => c.TypeName);
                ViewBag.TypeId = new SelectList(query.AsEnumerable(), "TypeID", "TypeName", 1);

                return View();
            }
            return RedirectToAction("Login", "Administrator");
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreateArticle(FormCollection collection)
        {
            bool logIn = HttpContext.Request.IsAuthenticated;
            if (logIn)
            {
                string sImage = collection["Images"];
                if (string.IsNullOrEmpty(sImage))
                {
                    sImage = "/Content/UpLoadImage/khatvongviet_logo.jpg";
                }
                string idType = collection["TypeId"];
                string title = collection["title"];
                string summary = collection["summary"];
                string context = collection["context"];
                string dateCreate = collection["datecreate"];

                var article = new Article
                {
                    TypeID = idType,
                    Title = title,
                    Summary = summary,
                    Context = context,
                    Image = sImage,
                    DateCreate = Convert.ToDateTime(dateCreate),
                    Email = null,
                    Publish = true
                };

                dataContext.Articles.AddObject(article);
                dataContext.SaveChanges();
                return RedirectToAction("ManageArticle", "Administrator");
            }
            return RedirectToAction("Login", "Administrator");
        }

        public ActionResult ManageArticle(string sortOrder, string currentFilter, string searchString, int? page)
        {
            bool logIn = HttpContext.Request.IsAuthenticated;
            if (logIn)
            {
                ViewBag.CurrentSort = sortOrder;
                ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
                ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

                if (searchString != null)
                {
                    page = 1;
                }
                else
                {
                    searchString = currentFilter;
                }

                ViewBag.CurrentFilter = searchString;

                var articles = from s in dataContext.Articles
                               where s.TypeID != "GocChiaSe_CXV"
                               select s;
                if (!String.IsNullOrEmpty(searchString))
                {
                    articles = articles.Where(s => s.Title.ToUpper().Contains(searchString.ToUpper()));
                }
                switch (sortOrder)
                {
                    case "name_desc":
                        articles = articles.OrderByDescending(s => s.Title);
                        break;
                    case "Date":
                        articles = articles.OrderBy(s => s.DateCreate);
                        break;
                    case "date_desc":
                        articles = articles.OrderByDescending(s => s.DateCreate);
                        break;
                    default:  // Name ascending 
                        articles = articles.OrderBy(s => s.Title);
                        break;
                }

                const int pageSize = 10;
                int pageNumber = (page ?? 1);
                return View(articles.ToPagedList(pageNumber, pageSize));
            }
            return RedirectToAction("Login", "Administrator");
        }

        public ActionResult ManageConfession(string sortOrder, string currentFilter, string searchString, int? page)
        {
            bool logIn = HttpContext.Request.IsAuthenticated;
            if (logIn)
            {
                ViewBag.CurrentSort = sortOrder;
                ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
                ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

                if (searchString != null)
                {
                    page = 1;
                }
                else
                {
                    searchString = currentFilter;
                }

                ViewBag.CurrentFilter = searchString;

                var articles = from s in dataContext.Articles
                               where s.TypeID == "GocChiaSe_CXV"
                               select s;
                if (!String.IsNullOrEmpty(searchString))
                {
                    articles = articles.Where(s => s.Title.ToUpper().Contains(searchString.ToUpper()));
                }
                switch (sortOrder)
                {
                    case "name_desc":
                        articles = articles.OrderByDescending(s => s.Title);
                        break;
                    case "Date":
                        articles = articles.OrderBy(s => s.DateCreate);
                        break;
                    case "date_desc":
                        articles = articles.OrderByDescending(s => s.DateCreate);
                        break;
                    default:  // Name ascending 
                        articles = articles.OrderBy(s => s.Title);
                        break;
                }

                const int pageSize = 10;
                int pageNumber = (page ?? 1);

                return View(articles.ToPagedList(pageNumber, pageSize));
            }
            return RedirectToAction("Login", "Administrator");
        }

        public ActionResult EditArticle(int id)
        {
            bool logIn = HttpContext.Request.IsAuthenticated;
            if (logIn)
            {
                Article article = getData.GetArticle(id);
                return View(article);
            }
            return RedirectToAction("Login", "Administrator");
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditArticle(FormCollection collection)
        {
            bool logIn = HttpContext.Request.IsAuthenticated;
            if (logIn)
            {
                int tempId = Convert.ToInt32(collection["ID"]);
                var article = dataContext.Articles.First(a => a.ID == tempId);

                string sImage = collection["Images"];
                string iIdType = collection["TypeId"];
                string sTitle = collection["Title"];
                string sContent = collection["Detail"];
                string dateCreate = collection["DateCreate"];
                string summary = collection["summary"];

                article.ID = Convert.ToInt32(collection["ID"]);
                article.TypeID = iIdType;
                article.Title = sTitle;
                article.Summary = summary;
                article.Publish = false;
                article.Context = sContent;
                article.DateCreate = Convert.ToDateTime(dateCreate);
                if (sImage != null)
                {
                    article.Image = sImage;
                }

                UpdateModel(article);

                dataContext.SaveChanges();
                return RedirectToAction("ManageArticle", "Administrator");
            }
            return RedirectToAction("Login", "Administrator");
        }

        public ActionResult EditConfession(int id)
        {
            bool logIn = HttpContext.Request.IsAuthenticated;
            if (logIn)
            {
                Article article = getData.GetArticle(id);
                return View(article);
            }
            return RedirectToAction("Login", "Administrator");
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditConfession(FormCollection collection)
        {
            bool logIn = HttpContext.Request.IsAuthenticated;
            if (logIn)
            {
                int tempId = Convert.ToInt32(collection["ID"]);
                var confession = dataContext.Articles.First(a => a.ID == tempId);

                string sTitle = collection["Title"];
                string sContent = collection["Context"];


                confession.ID = Convert.ToInt32(collection["ID"]);
                confession.TypeID = "GocChiaSe_CXV";
                confession.Title = sTitle;
                confession.Context = sContent;

                UpdateModel(confession);

                dataContext.SaveChanges();
                return RedirectToAction("ManageConfession", "Administrator");
            }
            return RedirectToAction("Login", "Administrator");
        }

        [HttpGet]
        public ActionResult DeleteArticle(int id)
        {
            bool logIn = HttpContext.Request.IsAuthenticated;
            if (logIn)
            {
                Article article = dataContext.Articles.SingleOrDefault(p => p.ID == id);
                dataContext.Articles.DeleteObject(article);
                dataContext.SaveChanges();
                return RedirectToAction("ManageArticle");
            }
            return RedirectToAction("Login", "Administrator");
        }

        [HttpGet]
        public ActionResult DeleteCofession(int id)
        {
            bool logIn = HttpContext.Request.IsAuthenticated;
            if (logIn)
            {
                Article article = dataContext.Articles.SingleOrDefault(p => p.ID == id);
                dataContext.Articles.DeleteObject(article);
                dataContext.SaveChanges();
                return RedirectToAction("ManageConfession");
            }
            return RedirectToAction("Login", "Administrator");
        }

        [HttpGet]
        public ActionResult ManageSlideShow(string picture)
        {
            bool logIn = HttpContext.Request.IsAuthenticated;
            if (logIn)
            {
                List<Article> listArticle = getData.GetListSlideShow();
                if (picture == "1")
                {
                    ViewBag.Number = 1;
                    return View(listArticle[0]);
                }
                ViewBag.Number = 2;
                return View(listArticle[1]);
            }
            return RedirectToAction("Login", "Administrator");
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult ManageSlideShow(FormCollection collection)
        {
            bool logIn = HttpContext.Request.IsAuthenticated;
            if (logIn)
            {
                int tempId = Convert.ToInt32(collection["ID"]);
                var slideShow = dataContext.Articles.First(a => a.ID == tempId);

                string tieuDe = collection["Title"];
                string noiDung = collection["Detail"];
                string hinhAnh = collection["Images"];


                slideShow.ID = Convert.ToInt32(collection["ID"]);
                slideShow.TypeID = "SlideShow";
                slideShow.Title = tieuDe;
                slideShow.Context = noiDung;
                slideShow.Image = hinhAnh;

                UpdateModel(slideShow);

                dataContext.SaveChanges();
                return RedirectToAction("Default", "Home");
            }
            return RedirectToAction("Login", "Administrator");
        }

        public ActionResult ManageMember(string role, string sortOrder, string currentFilter, string searchString, int? page)
        {
            bool logIn = HttpContext.Request.IsAuthenticated;
            if (logIn)
            {
                ViewBag.role = role;
                ViewBag.CurrentSort = sortOrder;
                ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";

                if (searchString != null)
                {
                    page = 1;
                }
                else
                {
                    searchString = currentFilter;
                }

                ViewBag.CurrentFilter = searchString;

                var members = from s in dataContext.Members
                               where s.RoleID == role
                               select s;
                if (!String.IsNullOrEmpty(searchString))
                {
                    members = members.Where(s => s.Name.ToUpper().Contains(searchString.ToUpper()));
                }
                switch (sortOrder)
                {
                    case "name_desc":
                        members = members.OrderByDescending(s => s.Name);
                        break;
                    default:  // Name ascending 
                        members = members.OrderBy(s => s.Name);
                        break;
                }

                const int pageSize = 10;
                int pageNumber = (page ?? 1);

                return View(members.ToPagedList(pageNumber, pageSize));
            }
            return RedirectToAction("Login", "Administrator");
        }

        [HttpGet]
        public ActionResult DeleteMember(int id, string role)
        {
            bool logIn = HttpContext.Request.IsAuthenticated;
            if (logIn)
            {
                Member member = dataContext.Members.SingleOrDefault(p => p.ID == id);
                dataContext.Members.DeleteObject(member);
                dataContext.SaveChanges();
                return RedirectToAction("ManageMember", new {role});
            }
            return RedirectToAction("Login", "Administrator");
        }

        public ActionResult EditMember(int id, string role)
        {
            bool logIn = HttpContext.Request.IsAuthenticated;
            if (logIn)
            {
                ViewBag.role = role;
                Member member = getData.GetMember(id);
                return View(member);
            }
            return RedirectToAction("Login", "Administrator");
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditMember(FormCollection collection)
        {
            bool logIn = HttpContext.Request.IsAuthenticated;
            if (logIn)
            {
                int tempId = Convert.ToInt32(collection["ID"]);
                var member = dataContext.Members.First(a => a.ID == tempId);
                string role = collection["Role"];
                string name = collection["Name"];
                string summary = collection["Summary"];
                string description = collection["Detail"];
                string photo = collection["Images"];


                member.ID = Convert.ToInt32(collection["ID"]);
                member.Name = name;
                member.Summary = summary;
                member.Description = description;
                member.Photo = photo;

                UpdateModel(member);

                dataContext.SaveChanges();
                return RedirectToAction("ManageMember", new {role });
            }
            return RedirectToAction("Login", "Administrator");
        }

        public ActionResult CreateMember()
        {
            bool logIn = HttpContext.Request.IsAuthenticated;
            if (logIn)
            {
                IEnumerable<SelectListItem> items = dataContext.RoleMembers
                                                        .Select(c => new SelectListItem
                                                        {
                                                            Value = c.RoleID,
                                                            Text = c.RoleName
                                                        });

                var query = dataContext.RoleMembers.Select(c => new { c.RoleID, c.RoleName });
                ViewBag.RoleId = new SelectList(query.AsEnumerable(), "RoleID", "RoleName", 1);

                return View();
            }
            return RedirectToAction("Login", "Administrator");
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CreateMember(FormCollection collection)
        {
            bool logIn = HttpContext.Request.IsAuthenticated;
            if (logIn)
            {
                string sImage = collection["Images"] ?? "/Content/UpLoadImage/khatvongviet_logo.jpg";

                string roleId = collection["RoleId"];
                string name = collection["name"];
                string summary = collection["summary"];
                string context = collection["context"];

                var member = new Member
                {
                    RoleID = roleId,
                    Name = name,
                    Summary = summary,
                    Description = context,
                    Photo = sImage
                };

                dataContext.Members.AddObject(member);
                dataContext.SaveChanges();
                return RedirectToAction("ManageMember", new { role = roleId });
            }
            return RedirectToAction("Login", "Administrator");
        }
    }
}
